package com.yuncheng.spcyApi.controller;

import java.lang.reflect.InvocationTargetException;
import java.util.*;
import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yuncheng.spcyApi.alog.annotation.Log;
import com.yuncheng.spcyApi.constant.common.LogConstant;
import com.yuncheng.spcyApi.constant.common.SpcyConstant;
import com.yuncheng.spcyApi.service.ISpcyLogService;
import com.yuncheng.spcyApi.utils.DateConvert;
import com.yuncheng.spcyApi.utils.GetUuIdUtils;
import com.yuncheng.spcyApi.vo.da.DaTypeTreeVo;
import com.yuncheng.vo.HttpResult;
import com.yuncheng.common.base.controller.BaseController;
import com.yuncheng.spcyApi.entity.SpcyDaType;
import com.yuncheng.spcyApi.service.ISpcyDaTypeService;
import com.yuncheng.spcyApi.vo.common.TreeTwoVo;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import utils.LogUtils;
import utils.ObjectToMapUtils;

/**
 * @Description: 审评查验-档案-档案分类
 * @Author: yuncheng
 * @Date: 2023-08-09
 * @Version: V1.0
 */
/*@Api(tags = "审评查验-档案-档案分类接口")
@RestController
@RequestMapping("/api/SpcyDaType/spcyDaType")*/
public class SpcyDaTypeController extends BaseController<SpcyDaType, ISpcyDaTypeService> {

    private static final Logger log = LoggerFactory.getLogger(SpcyDaTypeController.class);

    @Resource
    private ISpcyDaTypeService spcyDaTypeService;

    @Resource
    private ISpcyLogService spcyLogService;

    @Log(title = "档案分类-数组查询")
    @ApiOperation(value = "档案分类-数组查询")
    @GetMapping(value = "/queryPageList")
    public HttpResult<?> queryPageList(@RequestParam(value = "fflmc",defaultValue = "")String fflmc) {
        List<SpcyDaType> pageList = spcyDaTypeService.list(new LambdaQueryWrapper<SpcyDaType>()
                .like(StringUtils.isNotBlank(fflmc),SpcyDaType::getFflmc,fflmc)
                .orderByAsc(SpcyDaType::getForder));

        return HttpResult.ok(pageList);
    }

    @Log(title = "档案分类-树形结构查询")
    @ApiOperation(value = "档案分类-树形结构查询")
    @GetMapping(value = "getTreeTypeList")
    public HttpResult<?> getTreeTypeList(){
        List<DaTypeTreeVo> treeVoList = spcyDaTypeService.selectAllType(null);

        List<TreeTwoVo> treeList = new ArrayList<>();
        for (DaTypeTreeVo type : treeVoList){
            TreeTwoVo treeVo = new TreeTwoVo();
            treeVo.setKey(type.getId());
            treeVo.setValue(type.getFflmc());
            treeVo.setChildren(this.getTreeList(type.getChildren()));
            treeList.add(treeVo);
        }

        return HttpResult.ok(treeList);
    }

    /**
     * 递归-将树形数据组成treeVo结构数据
     * @param treeVoList
     * @return
     */
    public List<TreeTwoVo> getTreeList(List<DaTypeTreeVo> treeVoList){
        List<TreeTwoVo> treeList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(treeVoList)){
            for (DaTypeTreeVo type : treeVoList){
                TreeTwoVo treeVo = new TreeTwoVo();
                treeVo.setKey(type.getId());
                treeVo.setValue(type.getFflmc());
                treeVo.setChildren(this.getTreeList(type.getChildren()));
                treeList.add(treeVo);
            }
        }
        return treeList;
    }


    @Log(title = "档案分类-添加")
    @ApiOperation(value = "档案分类-添加")
    @PostMapping(value = "/add")
    public HttpResult<?> add(@RequestBody SpcyDaType spcyDaType) {
        if (StringUtils.isBlank(spcyDaType.getFflmc())){
            return HttpResult.error("请分类名称不能为空，请输入!");
        }

        // 判断该分类是否已存在
        List<SpcyDaType> typeList = spcyDaTypeService.list(new LambdaQueryWrapper<SpcyDaType>()
                .eq(SpcyDaType::getFflmc, spcyDaType.getFflmc()));
        if (CollectionUtils.isNotEmpty(typeList)){
            return HttpResult.error("当前分类【"+spcyDaType.getFflmc()+"】已经存在了！");
        }

        spcyDaType.setId(GetUuIdUtils.ReplaceUuId());
        boolean parentOrder = true; // 是否为父级，默认是
        if (StringUtils.isNotBlank(spcyDaType.getFparentid())){
            parentOrder = false;
        }

        // 排序为空时，父级自动排序
        if (spcyDaType.getForder() == null && parentOrder){
            List<SpcyDaType> parentList = spcyDaTypeService.list(new LambdaQueryWrapper<SpcyDaType>()
                    .isNull(SpcyDaType::getFparentid));
            int count = parentList.size() + 1;
            spcyDaType.setForder(count);
        }

        // 排序为空时，子级自动排序
        if (spcyDaType.getForder() == null && !parentOrder){
            List<SpcyDaType> childList = spcyDaTypeService.list(new LambdaQueryWrapper<SpcyDaType>()
                    .isNotNull(SpcyDaType::getFparentid)
                    .eq(SpcyDaType::getFparentid, spcyDaType.getFparentid()));
            int count = childList.size() + 1;
            spcyDaType.setForder(count);
        }

        boolean save = spcyDaTypeService.save(spcyDaType);
        if (!save){
            return HttpResult.error("保存失败，请联系管理员，并刷新重试");
        }
        String log = "新增档案分类类型：";
        Map<String, Object> logMap = ObjectToMapUtils.objectToMap(spcyDaType);
        log += LogUtils.MapToStringMethod(logMap);
        spcyLogService.addLogs(LogConstant.LOGS_DA_SYSTEM,log,spcyDaType.getId(), SpcyConstant.LOGS_SYS_TYPE_XZ,SpcyConstant.LOGS_SYS_TYPE_XZ);

        return HttpResult.ok("保存成功");
    }

    @Log(title = "档案分类-编辑")
    @ApiOperation(value = "档案分类-编辑")
    @PutMapping(value = "/edit")
    public HttpResult<?> edit(@RequestBody SpcyDaType spcyDaType) {
        SpcyDaType typeUpdate = spcyDaTypeService.getById(spcyDaType.getId());
        if (typeUpdate == null){
            return HttpResult.error("当前分类不存在，请刷新重试");
        }

        // 判断当前分类是否与旧分类相同，不同判断是否存在
        String oldType = typeUpdate.getFflmc(); // 旧的分类
        if (!oldType.equals(spcyDaType.getFflmc())){
            // 判断该分类是否已存在
            List<SpcyDaType> typeList = spcyDaTypeService.list(new LambdaQueryWrapper<SpcyDaType>()
                    .eq(SpcyDaType::getFflmc, spcyDaType.getFflmc()));
            if (CollectionUtils.isNotEmpty(typeList)){
                return HttpResult.error("当前分类【"+spcyDaType.getFflmc()+"】已经存在了！");
            }
        }

        Map<String, Object> oldMap = ObjectToMapUtils.objectToMap(typeUpdate);
        ConvertUtils.register(new DateConvert(), java.util.Date.class);
        // 自动完成页面到bean的数据对接
        try {
            BeanUtils.populate(typeUpdate, BeanUtils.describe(spcyDaType));
        } catch (IllegalAccessException e) {
            log.error("档案分类-类型-编辑更新失败[IllegalAccessException]: {}",e.getMessage());
        } catch (InvocationTargetException e) {
            log.error("档案分类-类型-编辑更新失败[InvocationTargetException]: {}",e.getMessage());
        } catch (NoSuchMethodException e) {
            log.error("档案分类-类型-编辑更新失败[]: {NoSuchMethodException}",e.getMessage());
        }
        boolean flag = spcyDaTypeService.updateById(typeUpdate);
        if (!flag){
            return HttpResult.error("保存失败,请联系管理员,并刷新重试");
        }
        String operContent = "档案分类-基本信息修改：";
        operContent += LogUtils.BeanModifyMsg(typeUpdate, oldMap);

        spcyLogService.addLogs(LogConstant.LOGS_DA_SYSTEM, operContent, typeUpdate.getId(), SpcyConstant.LOGS_SYS_TYPE_XG, SpcyConstant.LOGS_SYS_TYPE_XG);

        return HttpResult.ok("保存成功");
    }

    @Log(title = "档案分类-通过id删除")
    @ApiOperation(value = "档案分类-通过id删除")
    @DeleteMapping(value = "/delete")
    public HttpResult<?> delete(@RequestParam("id") String id) {
        if (StringUtils.isBlank(id)){
            return HttpResult.error("参数丢失，请联系管理员");
        }
        String log = "";

        SpcyDaType type = spcyDaTypeService.getById(id);
        if (type == null){
            return HttpResult.error("当前类型不存在，请刷新重试");
        }

        // 是否存在子级
        List<SpcyDaType> childList = spcyDaTypeService.list(new LambdaQueryWrapper<SpcyDaType>()
                .eq(SpcyDaType::getFparentid, id));
        if (CollectionUtils.isNotEmpty(childList)){
            return HttpResult.error("当前【"+type.getFflmc()+"】下存在子级，无法删除，请先删除子级。");
        }

        boolean delFlag = spcyDaTypeService.removeById(id);
        if (!delFlag){
            return HttpResult.error("删除失败，请联系管理员,并刷新重试");
        }
        log = "删除档案分类类型: ";
        Map<String, Object> logMap = ObjectToMapUtils.objectToMap(type);
        log += LogUtils.MapToStringMethod(logMap);
        spcyLogService.addLogs(LogConstant.LOGS_DA_SYSTEM,log,id, SpcyConstant.LOGS_SYS_TYPE_SC,SpcyConstant.LOGS_SYS_TYPE_SC);

        return HttpResult.ok("删除成功");
    }

    @Log(title = "档案分类-通过id查询")
    @ApiOperation(value = "档案分类-通过id查询")
    @GetMapping(value = "/queryById")
    public HttpResult<?> queryById(@RequestParam("id") String id) {
        SpcyDaType spcyDaType = spcyDaTypeService.getById(id);
        return HttpResult.ok(spcyDaType);
    }

}
